<?php

header('Content-Type: text/plain');

require_once('common.php');
require_once('RequestDispatcher.class.php');


// int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] )
function onError($errno, $errstr, $errfile, $errline) {
	$fullErrorMessage = sprintf("Error in %s:%s [ErrorNumber=%s] --- [%s]", $errfile, $errline, $errno, $errstr);
	Log::instance()->fatal($fullErrorMessage);
	throw new Exception("Fatal remote error! (See server logs for details)");
}

#set_error_handler("onError");

try {
	
	$envConfig = Configuration::getInstance();
	
	$log = Log::instance();
	$log->open($envConfig->getLogFileName(), $envConfig->getLogLevel());

	
	$dispatcher = new RequestDispatcher();
	$requestClass = $dispatcher->processGet($_GET);
	
	if(!isLoggedIn() &&
		$requestClass != 'UserLoginRequest' &&
	   	$requestClass != 'UserRegisterRequest' &&
	   	
	   	// these two are loaded at first by the client without need of login
	   	$requestClass != 'FetchUsersRequest' &&
	   	$requestClass != 'FetchCategoriesRequest'
	   ) {
		throw new Exception("User not yet logged in!");
		
	} else {
		$db = $envConfig->newPdoConnection();
		
		$includePath = 'request/' . $requestClass . '.class.php';
		Log::instance()->debug("Requiring class by path [$includePath].");
		require_once($includePath);
		$request = new $requestClass($db);
		$request->execute();
		
		$db = null;
	}
	
	$log->close();
} catch(Exception $e) {
	
	echo convertFatalError($e);
	
	Log::instance()->fatal("Uncaught exception was thrown", $e);
	$log->closeSaveIfNecessary();
}


function convertFatalError(Exception $exception) {
	$out = '<FatalError>';
	$out .= '<Message>' . wrapCData($exception->getMessage()) . '</Message>';
	$out .= '<Trace>See server logs for details</Trace>';
	
	// following could display sensitive data (db-structure, or even passwords):
	// $out .= '<Trace>' . wrapCData($exception->getTraceAsString()) . '</Trace>';
	
	$out .= '</FatalError>';
	return $out;
}

?>
